import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseInterceptors, UploadedFile, ParseFilePipeBuilder, Req, ParseIntPipe } from '@nestjs/common';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { getBookDto } from './dto/get-book.dto';
import { wrapperCountResponse, wrapperResponse } from '../../utils';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('book')
export class BookController {
  constructor(
    private readonly bookService: BookService
  ) {}

  // 创建图书
  @Post()
  createBook(@Body() createBookDto: CreateBookDto, @Req() req) {
    return wrapperResponse(
      this.bookService.addBook(createBookDto, req.user.username),
      '创建图书成功'
    )
  }

  // 获取所有图书
  @Get()
  findAll() {
    return this.bookService.findAll();
  }

  // 获取图书列表
  @Get('/list')
  getList(@Query() query: getBookDto) {
    return wrapperCountResponse(
      this.bookService.getBookList(query),
      this.bookService.getBookCount(query),
      '获取图书列表成功'
    );
  }

  // 获取所有分类
  @Get('/category')
  findCagetory() {
    return wrapperResponse(
      this.bookService.findCategoryAll(),
      '获取所有分类成功'
    )
  }

  // 查询图书详情
  @Get(':id')
  getBook(@Param('id', ParseIntPipe) id) {
    return wrapperResponse(
      this.bookService.getBook(id),
      '获取图书详情成功'
    );
  }

  // 上传文件
  @Post('/upload')
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile(
    new ParseFilePipeBuilder().addFileTypeValidator({ fileType: /epub/}).build()
  ) file: Express.Multer.File) {
    // console.log("🚀 ~ BookController ~ uploadFile ~ file:", file)
    return wrapperResponse(
      this.bookService.uploadFile(file),
      '上传文件成功'
    )
  }

  // 删除图书
  @Delete(':id')
  remove(@Param('id', ParseIntPipe) id: number) {
    console.log("🚀 ~ BookController ~ remove ~ id:", id)
    return wrapperResponse(
      this.bookService.remove(+id),
      '删除图书成功'
    )
  }

  // @Get(':id')
  // findOne(@Param('id') id: string) {
  //   return this.bookService.findOne(+id);
  // }

  // @Patch(':id')
  // update(@Param('id') id: string, @Body() updateBookDto: UpdateBookDto) {
  //   return this.bookService.update(+id, updateBookDto);
  // }

}
